package cn.com.fob001.vesselreminder;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.fob001.common.SQLHelper;
import cn.com.fob001.vesselreminder.bo.BOVessel;
import cn.com.fob001.vesselreminder.bo.BOVesselReminder;
import cn.com.fob001.vesselreminder.dao.VesselDAO;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

/**
 * 
 * @author
 * @version 1.0
 */
public class LaunchService extends Service {

	private static NotificationManager nm;
	private static Context context;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		// 获取系统的NotificationManager服务
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		context = getBaseContext();
		// 定义5秒执行一行输出
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				System.out.println("-----" + new Date() + "-----");
				
				BOVessel[] beans = VesselDAO.queryAll(SQLHelper.getConnection(context));

				if (beans == null || beans.length == 0) {
					return;
				}

				for (int i = 0; i < beans.length; i++) {
					MainActivity.queryVesselPlan(context, beans[i].getVesselname(), false);
				}

			}
		}, 0, 1000 * 1 * 60 * 60);
	}

	public static void sendNotification(BOVesselReminder bean) {

		// 发送通知
		// 创建一个启动其他Activity的Intent
		Intent intent = new Intent(context, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);

		PendingIntent pi = PendingIntent.getActivity(context,
				R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);

		Notification notify = new Notification(R.drawable.ic_launcher,
				"进箱计划提醒", System.currentTimeMillis());
		notify.defaults = Notification.DEFAULT_ALL;
		notify.flags = Notification.FLAG_AUTO_CANCEL;
		// "DA QING HE，915S，港区 WGQ5，开港时间：2013-06-12 06:00:00，截港时间：2013-06-12 06:00:00"
		String msg = new StringBuilder()
				.append(bean.getStatus())
				.append("，")
				.append(bean.getVesselname())
				.append("，").append(bean.getVoy()).append("，").append("港区：")
				.append(bean.getPort()).append("，开港时间：")
				.append(bean.getDopen()).append("，截港时间：")
				.append(bean.getDclose()).toString();

		notify.setLatestEventInfo(context, "进箱计划提醒", msg, pi);

		// 发送通知
		nm.notify(R.string.app_name, notify);
		System.out.println("发送通知消息");

	}
}